package galaxy.generator;

import java.util.LinkedList;
import java.util.List;

/**
 * Transforms a set of input symbols into
 */
public class Grammar {
	
	private List<Rule> rules;
	
	public Grammar()
	{
		this.rules = new LinkedList<Rule>(); 
	}
	
	public Grammar(List<Rule> rules)
	{
		this.rules = rules;
	}
	
	public Grammar add(Rule r)
	{
		rules.add(r);
		return this;
	}
	
	public List<Node> transform(List<Node> input)
	{
		for (Node s : input) {
			if (s.hasChildren()) {
				transform(s.getChildren());
			} else {
				transform(s);
			}
		}
		return input;
	}
	
	public Node transform(Node input)
	{
		if (input.hasChildren()) {
			transform(input.getChildren());
		} else {
			for (Rule r : rules) {
				if (r.accept(input)) {
					return r.apply(input);
				}
			}
		}
		return input;
	}
}
